<script setup name="Underreview">
import { View } from '@element-plus/icons-vue'
import { pcaTextArr } from 'element-china-area-data'
import Message from 'vue-m-message'
import userServices from '@/api/user/user.js'
import customerInformationService from '@/api/customerInformation/index.js'
import BaseForm from '@/components/BaseForm/BaseForm.vue'
import { isObject } from '@/utils/validate.js'
import ContractDraw from '@/views/system/contract/components/ContractDraw.vue'
import contractService from '@/api/contract/index.js'
import Toolbar from '@/components/Toolbar/Toolbar.vue'
import SearchBar from '@/components/SearchBar/SearchBar.vue'
import { useDict } from '@/utils/dict.js'

const { proxy } = getCurrentInstance()

const {
  sys_contract_type,
  sys_contractaame,
  sys_contract_status,
  sys_case_type,
  sys_product_name,
} = useDict('sys_contract_type', 'sys_contractaame', 'sys_contract_status', 'sys_case_type', 'sys_product_name')

const auditStatus = ref('0')
const tableLoading = ref(false)
const dialogVisible = ref(false)

const tabsList = [
  {
    name: '审核中',
    id: '0',
  },
  {
    name: '驳回修改',
    id: '2',
  },
]
const customerQueryList = ref([])
const salesmanOptions = ref([])
const queryParams = ref({})
const locationArea = ref([])

const searchConfig = ref([
  {
    label: '合同编号',
    field: 'contractNo',
    type: 'input',
    defaultShow: true,
  },
  {
    label: '合同类别',
    field: 'contractType',
    type: 'select',
    options: {
      data: sys_contract_type,
    },
    defaultShow: true,
  },
  {
    label: '客户所在区域',
    field: 'locationArea',
    type: 'custom',
    defaultShow: true,
  },
  {
    label: '客户名称',
    field: 'customerId',
    type: 'select',
    defaultShow: true,
    options: {
      data: customerQueryList,
      label: 'customerName',
      value: 'customerId',
    },
  },
  {
    label: '递交端口',
    field: 'deliveryWindow',
    type: 'input',
  },
  {
    label: '合同开始时间',
    field: 'contractStartTime',
    type: 'daterange',
  },
  {
    label: '业务经理',
    field: 'userId',
    type: 'input',
    // options: {
    //   data: salesmanOptions,
    //   label: 'nickName',
    //   value: 'userId',
    // },
  },
  {
    label: '备注',
    field: 'remark',
    type: 'input',
  },
])

// 表格数据
const tableData = ref([])
const tableColumns = ref([
  {
    type: 'checkbox',
    width: 50,
    align: 'center',
  },
  {
    type: 'seq',
    width: 60,
    align: 'center',
  },
  {
    title: '合同编号',
    field: 'contractNo',
    align: 'center',
    minWidth: 100,
  },
  {
    title: '合同类别',
    field: 'contractType',
    align: 'center',
    minWidth: 50,
    slots: {
      default: 'contractType',
    },
  },
  {
    title: '客户名称',
    field: 'customerName',
    align: 'center',
    minWidth: 95,
    showOverflow: 'tooltip',
  },
  {
    title: '客户所在区域',
    field: 'locationArea',
    align: 'center',
    minWidth: 95,
    showOverflow: 'tooltip',
  },
  {
    title: '递交端口',
    field: 'submitcompanyName',
    align: 'center',
    minWidth: 90,
  },
  {
    title: '合同开始时间',
    field: 'contractStartTime',
    align: 'center',
    minWidth: 100,
    formatter: ({ cellValue }) => {
      return cellValue ? cellValue.split(' ')[0] : ''
    },
  },
  { title: '业务经理', field: 'nickName', align: 'center', minWidth: 50 },
  {
    title: '状态',
    field: 'auditStatus',
    align: 'center',
    slots: { default: 'auditStatus'},
    minWidth: 50,
  },
  {
    title: '审核意见',
    field: 'auditSuggest',
    align: 'center',
    minWidth: 110,
  },
  { title: '备注', field: 'remark', align: 'center', minWidth: 100 },
  {
    title: '操作',
    field: 'action',
    align: 'center',
    minWidth: 200,
    fixed: 'right',
    slots: {
      default: 'action',
    },
  },
])

const ids = ref([])
const pagerConfig = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10,
})
const contractId = ref(null)
const isView = ref(false)
const reviewVisible = ref(false)
const reviewFormData = ref({
  auditStatus: '1',
  auditSuggest: '审核已通过',
})
const reviewForm = ref([
  {
    label: '是否通过',
    field: 'auditStatus',
    type: 'radio',
    span: 24,
    rules: [
      {
        required: true,
        message: '请选择是否通过',
        trigger: 'change',
      },
    ],
    options: {
      data: [
        {
          value: '1',
          label: '通过',
        },
        {
          value: '2',
          label: '不通过',
        },
      ],
    },
  },
  {
    label: '审核意见',
    field: 'auditSuggest',
    type: 'input',
    span: 24,
    rules: [
      {
        required: true,
        message: '请输入审核意见',
        trigger: 'blur',
      },
    ],
  },
])

onMounted(() => {
  getList()
  getOptionsList()
})

function getOptionsList() {
  customerInformationService.getQueryList().then((res) => {
    customerQueryList.value = res.data
  })
  userServices.getSalesmanList().then((res) => {
    salesmanOptions.value = res.data
  })
}
function getList() {
  tableLoading.value = true
  const params = {
    ...queryParams.value,
    auditStatus: auditStatus.value,
    pageSize: pagerConfig.value.pageSize,
    pageNum: pagerConfig.value.currentPage,
  }
  contractService.list(params).then((res) => {
    tableData.value = res.rows
    pagerConfig.value.total = res.total
    tableLoading.value = false
  })
}

function handleSearch(e, type) {
  if (type === 'reset') {
    locationArea.value = []
  }
  queryParams.value = {
    ...e,
    locationArea: locationArea.value ? locationArea.value.join('/') : null,
    contractStartTimeMin: e.contractStartTime ? e.contractStartTime[0] : null,
    contractStartTimeMax: e.contractStartTime ? e.contractStartTime[1] : null,
  }
  delete queryParams.value.contractStartTime
  pagerConfig.value.currentPage = 1
  pagerConfig.value.pageSize = 10
  getList()
}

function handleExport() {
  proxy.download('system/contract/export', { ...queryParams.value, exportIds: ids.value.join(',') }, `contract__${new Date().getTime()}.xlsx`)
}

function handleTabChange() {
  queryParams.value = {}
  pagerConfig.value.currentPage = 1
  pagerConfig.value.pageSize = 10
  getList()
}

async function handleAdd() {
  contractId.value = null
  isView.value = false
  dialogVisible.value = true
}

function handlePageChange({ currentPage, pageSize }) {
  pagerConfig.value.currentPage = currentPage
  pagerConfig.value.pageSize = pageSize
  getList()
}

function handleDialogVisible(val) {
  if (isObject(val)) {
    dialogVisible.value = false
    queryParams.value = {}
    pagerConfig.value.currentPage = 1
    pagerConfig.value.pageSize = 10
    getList()
  }
}

function handleEdit(id) {
  contractId.value = id
  isView.value = false
  dialogVisible.value = true
}

function handleView(id) {
  contractId.value = id
  isView.value = true
  dialogVisible.value = true
}

function handleDelete(id) {
  contractService.del(id).then(() => {
    Message.success('删除成功')
    getList()
  })
}

function handleReview(id) {
  reviewFormData.value.contractId = id
  reviewVisible.value = true
}

function handleReviewVisibleClose() {
  reviewFormData.value = {
    auditStatus: '1',
    auditSuggest: '',
  }
  reviewVisible.value = false
}

function handleReviewSubmit() {
  contractService.audit(reviewFormData.value).then(() => {
    Message.success('审核成功')
    handleReviewVisibleClose()
    getList()
  })
}
</script>

<template>
  <div class="app-container">
    <el-card shadow="never">
      <el-tabs v-model="auditStatus" @tab-change="handleTabChange()">
        <el-tab-pane v-for="item in tabsList" :key="item.id" :label="item.name" :name="item.id" />
      </el-tabs>
      <SearchBar :search-config="searchConfig" @search="handleSearch">
        <template #locationArea>
          <el-cascader
            v-model="locationArea"
            :options="pcaTextArr"
            size="default"
            placeholder="请选择所属区域"
            clearable
            class="w-full"
          />
        </template>
      </SearchBar>
    </el-card>
    <el-card shadow="never" class="mt-5">
      <Toolbar>
        <el-button
          v-hasPermi="['system:contract:add']"
          type="primary"
          class="el-gradient-primary"
          @click="handleAdd"
        >
          新增
          <el-icon class="el-icon--right">
            <CirclePlusFilled />
          </el-icon>
        </el-button>
        <el-button
          v-hasPermi="['system:contract:export']"
          type="warning"
          class="el-gradient-warning"
          @click="handleExport()"
        >
          导出
          <el-icon class="el-icon--right">
            <FolderAdd />
          </el-icon>
        </el-button>
      </Toolbar>
      <vxe-grid
        :row-config="{ keyField: 'contractId' }"
        :data="tableData"
        :columns="tableColumns"
        :loading="tableLoading"
        :pager-config="pagerConfig"
        header-cell-class-name="headerCellClass"
        @page-change="handlePageChange"
        max-height="500px"
      >
        <template #contractType="{ row }">
          <dict-tag :options="sys_contract_type" :value="row.contractType" />
        </template>
        <template #auditStatus="{ row }">
          <dict-tag :options="sys_contract_status" :value="row.auditStatus" />
        </template>
        <template #action="{ row }">
          <el-button
            v-show="auditStatus === '0'"
            v-hasPermi="['system:contract:audit']"
            size="small"
            type="primary"
            text
            @click="handleReview(row.contractId)"
          >
            审核
          </el-button>
          <el-button
            v-show="auditStatus === '2'"
            v-hasPermi="['system:contract:editht']"
            size="small"
            text
            type="success"
            icon="el-icon-edit"
            @click="handleEdit(row.contractId)"
          >
            修改
          </el-button>
          <!-- -->
          <span v-hasPermi="['system:contract:remove']">
            <el-popconfirm
              title="确认删除该合同？"
              @confirm="handleDelete(row.contractId)"
            >
              <template #reference>
                <el-button
                  size="small"
                  text
                  type="danger"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </span>
          <el-button
            size="small"
            text
            type="info"
            @click="handleView(row.contractId)"
          >
            查看
          </el-button>
        </template>
      </vxe-grid>
    </el-card>
    <ContractDraw
      v-model:visible="dialogVisible"
      :contract-id="contractId"
      :form-disabled="isView"
      @update:visible="handleDialogVisible"
    />
    <el-dialog
      v-model="reviewVisible"
      title="审核"
      width="26%"
      class="custom-dialog"
      :append-to-body="true"
      :destroy-on-close="true"
      @close="handleReviewVisibleClose"
    >
      <template #header>
        <div class="dialog-header">
          <span class="relative top-3 text-[16px]">
            审核
          </span>
        </div>
      </template>
      <BaseForm :field-list="reviewForm" :model="reviewFormData" @cancel="handleReviewVisibleClose" @submit="handleReviewSubmit" />
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
</style>
